package com.xinghou.platform.server.api.bussiness.impl;

import java.io.IOException;
import java.nio.file.Path;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Resource;

import com.xinghou.platform.dao.main.*;
import com.xinghou.platform.model.main.*;
import com.xinghou.platform.server.api.common.ImageComb;
import com.xinghou.platform.server.api.log.LoggerFactory;
import com.xinghou.platform.util.*;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import com.xinghou.platform.entity.req.ShareInfoReq;
import com.xinghou.platform.entity.resp.ShareInfoPhotoResp;
import com.xinghou.platform.entity.resp.ShareInfoResp;
import com.xinghou.platform.server.api.bussiness.SearchInfoBusinessService;
import com.xinghou.platform.server.api.bussiness.ShareInfoBusinessService;
import com.xinghou.platform.server.api.bussiness.ShopInfoBusinessService;
import com.xinghou.platform.server.api.bussiness.UserInfoBusinessService;
import com.xinghou.platform.server.api.service.SharedCardLuceneApiService;
import com.xinghou.platform.server.api.service.StoreLuceneApiService;
import com.xinghou.platform.server.api.service.UserLuceneApiService;

@Service("searchInfoService")
public class SearchInfoBusinessServiceImpl implements SearchInfoBusinessService {

    private Logger log = LoggerFactory.getServerInfoLogger(SearchInfoBusinessServiceImpl.class);


    private static String photominuri = ConfigUtil.getProperty("file_download");
    private static String photouri = ConfigUtil.getProperty("file_download");
    private static String url = ConfigUtil.getProperty("shopimage_download");
    @Resource
    private StoreLuceneApiService storeLuceneApiService;
    @Resource
    private StoreImageDAO storeImageDAO;
    @Resource
    private ShopInfoBusinessService shopInfoBusinessService;
    @Resource
    private UserLuceneApiService userLuceneApiService;
    @Resource
    private UserDAO userDAO;

    @Resource
    private UserStatisticsDAO userStatisticsDAO;
    @Resource
    private InterestTagsDAO interestTagsDAO;
    @Resource
    private DataConfigDAO dataConfigDAO;
    @Resource
    private StoreDAO storeDAO;
    @Resource
    private PhotoDAO photoDAO;
    @Resource
    private ShareInfoBusinessService shareInfoBusinessService;
    @Resource
    private UserInfoBusinessService userInfoBusinessService;
    @Resource
    private SharedCardLuceneApiService sharedCardLuceneApiService;
    @Resource
    private SharedCardImageDAO sharedCardImageDAO;
    @Resource
    private SharedCardPraiseDAO sharedCardPraiseDAO;
    @Resource
    private SharedCardDAO sharedCardDAO;
    @Resource
    private UserGeoDAO userGeoDAO;
    @Resource
    private UserSignaturesDAO userSignaturesDAO;

    @Resource
    private CityDAO cityDAO;


    @Override
    public List<ShareInfoResp> getShopInfos(ShareInfoReq shareInfoReq) {
        ShareInfoResp shareInfoResp = null;
        List<ShareInfoResp> shareInfoResps = new ArrayList<ShareInfoResp>();
        List<Store> stores;
        String distince = shareInfoReq.getDistance();
        int pagesize=(Integer.parseInt(shareInfoReq.getPagesize()));
        int fromno = (Integer.parseInt(shareInfoReq.getPageno()) - 1) * pagesize;
        try {
            if(!StringUtils.isBlank(shareInfoReq.getLevel())&&Double.parseDouble(shareInfoReq.getLevel())<12.5){
                List<SearchPolymerization> list  =storeLuceneApiService.getSearchPolymerization(true,shareInfoReq.getKey(), Double.parseDouble(distince), Double.parseDouble(shareInfoReq.getLongitude()), Double.parseDouble(shareInfoReq.getLatitude()),Double.parseDouble(shareInfoReq.getLevel()),null,null);
                for(SearchPolymerization searchPolymerization :list) {
                    if(searchPolymerization==null) continue;
                    shareInfoResp = new ShareInfoResp();
                    shareInfoResp.setCount(String.valueOf(searchPolymerization.getCount()));
                    shareInfoResp.setLatitude(searchPolymerization.getLatitude());
                    shareInfoResp.setLongitude(searchPolymerization.getLongitude());
                    shareInfoResps.add(shareInfoResp);
                }
            }else{
            stores = storeLuceneApiService.getSearchStoreInfos(shareInfoReq.getKey(), Integer.valueOf(fromno), pagesize, null, Double.parseDouble(distince), Double.parseDouble(shareInfoReq.getLongitude()), Double.parseDouble(shareInfoReq.getLatitude()));
            if (stores == null || stores.isEmpty()) return shareInfoResps;
            for (Store store : stores) {
                store = storeDAO.getStoreBystoreId(store.getId());
                if(store==null) continue;
                shareInfoResp = new ShareInfoResp();
                shareInfoResp.setShopname(store.getName());//门店
                shareInfoResp.setShopid(store.getId().toString());
                shareInfoResp.setShopaddress(store.getAddress());//地址
                shareInfoResp.setShoppurl(PhotoPathUtil.getHeader50w50h(ImageComb.combStoreUrl(store.getThumurl())));
                shareInfoResp.setThumurl(PhotoPathUtil.getStore400w300h(ImageComb.combStoreUrl(store.getThumurl())));
                //获取门店分类
                shareInfoResp.setCategory(getStoreCategoryDesc(store.getCategory_num()));
                shareInfoResp.setStorecardcount(store.getSharecount()==null?0+"":store.getSharecount().toString());
                String storeLon = String.valueOf(store.getLongitude());
                String storeLat = String.valueOf(store.getLatitude());
                shareInfoResp.setLongitude(storeLon);
                shareInfoResp.setLatitude(storeLat);
                if(!StringUtils.isEmpty(storeLon)&&!StringUtils.isEmpty(storeLat)&&!StringUtils.isEmpty(shareInfoReq.getLongitude())&&!StringUtils.isEmpty(shareInfoReq.getLatitude())) {
                   String dist = getDistance(Double.parseDouble(storeLon),Double.parseDouble(storeLat),Double.parseDouble(shareInfoReq.getLongitude()),Double.parseDouble(shareInfoReq.getLatitude()));
                    shareInfoResp.setDistance(dist);
                }else{
                    shareInfoResp.setDistance("");
                }

                shareInfoResps.add(shareInfoResp);
            }

            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return shareInfoResps;
    }


    public String getStoreCategoryDesc(String categorynums) {
        if(StringUtils.isBlank(categorynums)){
            return null;
        }
        String temp[] = categorynums.split("-");
        String v = "";
        int t = 0;
        for (int i = 0; i < temp.length; i++) {
            try {
                t = Integer.parseInt(temp[i]);
            } catch (Exception e) {
                continue;
            }
            DataConfig dataConfig = dataConfigDAO.getDataConfigByTag_id(t, 3);
            if (dataConfig == null) continue;
            ;
            String typename = dataConfig.getName();
            v = v + typename;
            if (i != temp.length - 1)
                v = v + "-";
        }
        return v;

    }
    /**
     * type 0:用户  1:手艺人
     */
    public List<ShareInfoResp> getFriendInfos(ShareInfoReq shareInfoReq, int type) {
        List<User> users;
        List<ShareInfoResp> shareInfoResps = new ArrayList<ShareInfoResp>();
        ShareInfoResp shareInfoResp = null;
        try {
            int pagesize = Integer.parseInt(shareInfoReq.getPagesize());
            int fromno = (Integer.parseInt(shareInfoReq.getPageno()) - 1) * pagesize;
            Double distance=Double.parseDouble(shareInfoReq.getDistance());
           if(!StringUtils.isBlank(shareInfoReq.getLevel())&&Double.parseDouble(shareInfoReq.getLevel())<12.5){
                List<SearchPolymerization> list  =storeLuceneApiService.getSearchPolymerization( false, shareInfoReq.getKey(), distance, Double.parseDouble(shareInfoReq.getLongitude()), Double.parseDouble(shareInfoReq.getLatitude()), Double.parseDouble(shareInfoReq.getLevel()), String.valueOf(type), shareInfoReq.getCitycode());
                for(SearchPolymerization searchPolymerization :list) {
                    if(searchPolymerization==null) continue;
                    shareInfoResp = new ShareInfoResp();
                    shareInfoResp.setCount(String.valueOf(searchPolymerization.getCount()));
                    shareInfoResp.setLatitude(searchPolymerization.getLatitude());
                    shareInfoResp.setLongitude(searchPolymerization.getLongitude());
                    shareInfoResps.add(shareInfoResp);
                }
            }else {
                Long time1 =System.currentTimeMillis();
                users = userLuceneApiService.getSearchUserInfos(shareInfoReq.getKey(), fromno, pagesize, String.valueOf(type), shareInfoReq.getCitycode(), distance, Double.parseDouble(shareInfoReq.getLongitude()), Double.parseDouble(shareInfoReq.getLatitude()));
               Long time2 =System.currentTimeMillis();
                log.info("solr select time is ===={}ms" ,time2-time1);
                if (users == null || users.isEmpty()) return shareInfoResps;
                for (User userInfo : users) {
                    shareInfoResp = new ShareInfoResp();
                    shareInfoResp.setUserid(String.valueOf(userInfo.getUserid()));
                    User user1 = userDAO.getUserById(userInfo.getUserid());
                    if (user1 == null) continue;
                    UserGeo userGeo = userGeoDAO.getUserGeoById(user1.getUserid());
                    UserSignatures signatures = userSignaturesDAO.getUserSignatures(user1.getUserid());
                    if (signatures != null)
                        shareInfoResp.setSignatures(signatures.getSignatures());
                    UserStatistics userStatistics = userStatisticsDAO.getUserStatById(user1.getUserid());
                    if (userStatistics != null) {
                        shareInfoResp.setSharecardcount(userStatistics.getSharecount().toString());
                    }
                    shareInfoResp.setHeadurl(PhotoPathUtil.getHeader50w50h(ImageComb.combHeaderUrl(user1.getHeadurl())));
                    shareInfoResp.setNickname(user1.getNickname());
                    shareInfoResp.setAgeyear(user1.getAgeyear());
                    shareInfoResp.setTastedesc(userInfoBusinessService.getInterestTagsTitleOfUser(user1.getTaste()));
                    shareInfoResp.setSex(user1.getSex() == null ? "" : user1.getSex().toString());
                    String userLon = userGeo == null ? "" : String.valueOf(userGeo.getLongitude());
                    String userLat =userGeo == null ? "" : String.valueOf(userGeo.getLatitude());
                    shareInfoResp.setLongitude(userLon);
                    shareInfoResp.setLatitude(userLat);

                    if(!StringUtils.isEmpty(userLon)&&!StringUtils.isEmpty(userLat)&&!StringUtils.isEmpty(shareInfoReq.getLongitude())&&!StringUtils.isEmpty(shareInfoReq.getLatitude())) {
                        String dist = getDistance(Double.parseDouble(userLon),Double.parseDouble(userLat),Double.parseDouble(shareInfoReq.getLongitude()),Double.parseDouble(shareInfoReq.getLatitude()));
                        shareInfoResp.setDistance(dist);
                    }else{
                        shareInfoResp.setDistance("");
                    }

                    shareInfoResps.add(shareInfoResp);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return shareInfoResps;
    }


    @Override
    public List<ShareInfoResp> getCardInfos(ShareInfoReq shareInfoReq) {
        ShareInfoResp shareInfoResp;
        StringBuilder sb;
        List<ShareInfoResp> shareInfoResps = new ArrayList<ShareInfoResp>();
        //List<SharedCard> sharedCards = sharedCardApiService.getSharedCardlist(10,num,shareInfoReq.getKey());
        List<SharedCard> sharedCards;
        try {
            int fromno = (Integer.parseInt(shareInfoReq.getFromno()) - 1) * 10;
            sharedCards = sharedCardLuceneApiService.getSearchSharedCards(shareInfoReq.getKey(), fromno, 10);
            if (sharedCards == null || sharedCards.isEmpty()) return shareInfoResps;
            for (SharedCard sharedCard : sharedCards) {
                if (sharedCard.getSharetype() == 2) {
                    continue;
                }
                shareInfoResp = new ShareInfoResp();
                shareInfoResp.setUserid(sharedCard.getUserid().toString());
                setUserInfo(shareInfoResp);
                Store store = storeDAO.getStoreBystoreId(sharedCard.getStoreid());
                shareInfoResp.setShopid(store.getId().toString());
                shareInfoResp.setShopname(store.getName());

                shareInfoResp.setIsfollow(String.valueOf(shareInfoBusinessService.getisfollow(shareInfoReq.getUserid(), sharedCard.getUserid().toString())));
                List<InterestTags> interestTagslist = interestTagsDAO.getInterestTagsByUserId(sharedCard.getStoreid());

                sb = new StringBuilder();
                for (InterestTags interestTags : interestTagslist) {
                    sb.append(dataConfigDAO.getDataConfigByTag_id(interestTags.getTagId(), 1).getName());
                    for (int i = 0; i < interestTagslist.size(); i++) {
                        sb.append("-");
                    }
                }
                SharedCardPraise sharedCardPraise = sharedCardPraiseDAO.getSharedCardPraiseStatusByid(sharedCard.getCardid(), Integer.parseInt(shareInfoReq.getUserid()));
                int status = 0;
                if (sharedCardPraise != null) {
                    status = sharedCardPraise.getStatus();
                }
                shareInfoResp.setIsUpvote(String.valueOf(status));
                shareInfoResp.setShareid(String.valueOf(sharedCard.getCardid()));
                shareInfoResp.setSharetype(sharedCard.getSharetype().toString());
                shareInfoResp.setContent(sharedCard.getContent());
                shareInfoResp.setStatus(sharedCard.getStatus().toString());
                shareInfoResp.setPraisecount(sharedCardDAO.getSharedCardBycardId(sharedCard.getCardid()).getPraisecount().toString());
                //shareInfoResp.setPraisecount(sharedCard.getPraiseCount().toString());
                if (shareInfoResp.getUserid().toString().equals(sharedCard.getUserid())) {
                    shareInfoResp.setDelTag("1");
                } else {
                    shareInfoResp.setDelTag("0");
                }
                shareInfoResp.setViewcount(sharedCardDAO.getSharedCardBycardId(sharedCard.getCardid()).getBrowsecount().toString());
                shareInfoResp.setPhotourllist(sharedCardImageDAO.getSharedCardImagelist(sharedCard.getCardid()));

                shareInfoResp.setDate(sharedCard.getCreatetime().toString());
                shareInfoResp.setTastelist(sb.toString());
                User user = userDAO.getUserById(sharedCard.getUserid());
                shareInfoResp.setShopjob("");
                if (user.getStoreid() != null) {
                    String artname = user.getName();
                    String jobinfos = "";
                    if (StringUtils.isNotBlank(artname)) {
                        String[] jobs = artname.split("--");
                        for (int i = 0; i < jobs.length; i++) {
                            jobinfos = jobinfos + dataConfigDAO.getDataConfigByTag_id(Integer.valueOf(jobs[i].split("-")[0]), 2).getName() + "-" + jobs[i].split("-")[1] + "--";
                        }
                        shareInfoResp.setShopjob(StringUtils.removeEnd(jobinfos, "--"));
                    }
                }
                Photo photo = photoDAO.getPhotoById(user.getHeadid());
                if (photo != null) {
                    shareInfoResp.setSimphotourl(PhotoPathUtil.getDB160(photominuri + photo.getPhotoUri()));
                    shareInfoResp.setPhotourl(photouri + photo.getPhotoUri());
                }
                shareInfoResp.setDistance(shopInfoBusinessService.distanceShopAndUser(shareInfoReq.getUserid(), String.valueOf(sharedCard.getStoreid())));
                //TODO 3.0版本新增的字段
                SharedCard card = sharedCardDAO.getSharedCardBycardId(sharedCard.getCardid());
                if (card != null) {
                    shareInfoResp.setDiscount(card.getDiscount());
                    if (card.getMoney() != null) {
                        shareInfoResp.setMoney(card.getMoney().toString());
                    } else {
                        shareInfoResp.setMoney("0");
                    }
                }
                SharedCardImage sharedCardImage = sharedCardImageDAO.getSharedCardImageByCardId(card.getCardid());
                if (sharedCardImage != null) {
                    String uri = sharedCardImage.getUri();
                    int index = uri.lastIndexOf("/");
                    if (index == -1) {
                        index = uri.lastIndexOf("\\");
                    }
                    if (index != -1) {
                        shareInfoResp.setSimcardphotourl(photominuri + uri.substring(0, index + 1) + "160" + uri.substring(index + 1, uri.length()));
                    }
                    shareInfoResp.setCardphotourl(photouri + uri);
                } else {
                    StoreImage storeImage = storeImageDAO.getStoreImageList(card.getStoreid(), 999);//取门面图片
                    if (storeImage != null) {
                        shareInfoResp.setSimcardphotourl(url + storeImage.getUri());
                        shareInfoResp.setPhotourl(url + storeImage.getUri());
                    }
                }
                //-------
                shareInfoResps.add(shareInfoResp);
            }
            //sortList(shareInfoResps);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return shareInfoResps;
    }


    private void setUserInfo(ShareInfoResp shareInfoResp) {
        User user = userDAO.getUserById(Integer.valueOf(shareInfoResp.getUserid()));
        if (user != null) {
            shareInfoResp.setSex(user.getSex().toString());
            shareInfoResp.setNickname(user.getNickname());
            shareInfoResp.setHoroscope(Gethoroscope.getConstellation(user.getBirthday()));
            shareInfoResp.setAge(DateUtils.getAge(user.getBirthday()));
            shareInfoResp.setSignname(user.getSignature());
            shareInfoResp.setSimphotourl("");
            shareInfoResp.setPhotourl("");
            shareInfoResp.setHeadurl("");
            if (user.getHeadid() != null) {
                Photo photo = photoDAO.getPhotoById(user.getHeadid());
                if (photo != null) {
                    shareInfoResp.setHeadurl(PhotoPathUtil.getDB160(photominuri + photo.getPhotoUri()));
                    shareInfoResp.setSimphotourl(PhotoPathUtil.getDB160(photominuri + photo.getPhotoUri()));
                    shareInfoResp.setPhotourl(photouri + photo.getPhotoUri());
                }
            }
        }
    }

    /**
     * 根据距离排序
     *
     * @param shareInfoResps
     */
    public void sortList(List<ShareInfoResp> shareInfoResps) {
        Collections.sort(shareInfoResps, new Comparator<ShareInfoResp>() {
            public int compare(ShareInfoResp arg0, ShareInfoResp arg1) {
                if ((Double.valueOf(arg0.getDistance()) - Double.valueOf((arg1.getDistance()))) < 0) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
    }

    /**
     * 根据时间排序
     *
     * @param shareInfoResps
     */
    public void sortTimeList(List<ShareInfoResp> shareInfoResps) {
        Collections.sort(shareInfoResps, new Comparator<ShareInfoResp>() {
            public int compare(ShareInfoResp arg0, ShareInfoResp arg1) {
                long ret = Long.parseLong(DateUtils.getNewZhCNDateTime(DateUtils.getDate(arg0.getDate()))) - Long.parseLong(DateUtils.getNewZhCNDateTime(DateUtils.getDate(arg1.getDate())));
                if (ret < 0) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
    }

    public static String getDistance(double long1, double lat1, double long2,
                                  double lat2) {
        double a, b, R;
        R = 6378137; // 地球半径
        lat1 = lat1 * Math.PI / 180.0;
        lat2 = lat2 * Math.PI / 180.0;
        a = lat1 - lat2;
        b = (long1 - long2) * Math.PI / 180.0;
        double d;
        double sa2, sb2;
        sa2 = Math.sin(a / 2.0);
        sb2 = Math.sin(b / 2.0);
        d = 2
                * R
                * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1)
                * Math.cos(lat2) * sb2 * sb2));
        return String.valueOf(d);
    }
}
